package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.query.QueryForObject;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.PermissionName;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("role")
public class RoleController {
    @Autowired
    private IRoleService roleService;

    /*创建一个方法来确定*/
    @RequiresPermissions("role:index")
    @PermissionName("角色主页")
    @RequestMapping("index")
    public String index() {
        //查找到并共享
        return "role/list";
    }

    @RequiresPermissions("role:list")
    @PermissionName("角色列表")
    @ResponseBody
    @RequestMapping("list")
    public PageResult list(@ModelAttribute("qo") QueryForObject qo) {
        System.err.println(JSON.toJSONString(roleService.query(qo)));
        return roleService.query(qo);
    }

    @RequestMapping("queryRoles")
    @ResponseBody
    public List<Role> queryRoles() {
        return roleService.selectAll();
    }

    @RequestMapping("getRoleIdByEmpId")
    @ResponseBody
    public List<Long> queryRoles(Long empId) {
        return roleService.getRoleIdByEmpId(empId);
    }

    @RequestMapping("save")
    @ResponseBody
    @RequiresPermissions("role:save")
    @PermissionName("角色保存")
    public JsonResult save(Role entity) {
        JsonResult result = new JsonResult();
        try {
            roleService.insert(entity);
        } catch (Exception e) {
            e.printStackTrace();
            result = new JsonResult("保存操作失败");
        }
        return result;
    }

    @RequestMapping("update")
    @ResponseBody
    @RequiresPermissions("role:update")
    @PermissionName("角色更新")
    public JsonResult update(Role entity) {
        JsonResult result = new JsonResult();
        try {
            roleService.updateByPrimaryKey(entity);
        } catch (Exception e) {
            e.printStackTrace();
            result = new JsonResult("更新操作失败");
        }
        return result;
    }

    @RequestMapping("delete")
    @ResponseBody
    @RequiresPermissions("role:delete")
    @PermissionName("角色删除")
    public JsonResult delete(Long id) {
        JsonResult result = new JsonResult();
        try {
            roleService.deleteByPrimaryKey(id);
        } catch (Exception e) {
            e.printStackTrace();
            result = new JsonResult("删除操作失败");
        }
        return result;
    }
}